<template>
  <ArtSearchBar
    ref="searchBarRef"
    v-model="formData"
    :items="formItems"
    :rules="rules"
    @reset="handleReset"
    @search="handleSearch"
  >
  </ArtSearchBar>
</template>

<script setup lang="ts">
  interface Props {
    modelValue: Record<string, any>
  }
  interface Emits {
    (e: 'update:modelValue', value: Record<string, any>): void
    (e: 'search', params: Record<string, any>): void
    (e: 'reset'): void
  }
  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 表单数据双向绑定
  const searchBarRef = ref()
  const formData = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
  })

  // 校验规则
  const rules = {}

  // 注册来源选项
  const registerSourceOptions = ref([
    { label: '全部', value: '' },
    { label: 'APP', value: 'app' },
    { label: '小程序', value: 'miniprogram' }
  ])

  // 性别选项
  const genderOptions = ref([
    { label: '全部', value: '' },
    { label: '男', value: '1' },
    { label: '女', value: '2' },
    { label: '未知', value: '0' }
  ])

  // 表单配置
  const formItems = computed(() => [
    {
      label: '名称',
      key: 'name',
      type: 'input',
      placeholder: '请输入用户名称',
      clearable: true
    },
    {
      label: 'OpenID',
      key: 'openid',
      type: 'input',
      placeholder: '请输入OpenID',
      clearable: true
    },
    {
      label: '注册来源',
      key: 'registerSource',
      type: 'select',
      props: {
        placeholder: '请选择注册来源',
        options: registerSourceOptions.value
      }
    },
    {
      label: '性别',
      key: 'gender',
      type: 'select',
      props: {
        placeholder: '请选择性别',
        options: genderOptions.value
      }
    },
    {
      label: '手机号',
      key: 'phone',
      type: 'input',
      props: { placeholder: '请输入手机号', maxlength: '11' }
    }
  ])

  // 事件
  function handleReset() {
    console.log('重置表单')
    emit('reset')
  }

  async function handleSearch() {
    await searchBarRef.value.validate()
    emit('search', formData.value)
    console.log('表单数据', formData.value)
  }
</script>

